<template>
  <div>
    <el-dialog :title="ruleForm.id == '' ? '添加整治任务' : '编辑整治任务'" :visible.sync="addEditIsDialog_c"
      @close="resetForm('formName')" width="800px">
      <el-form :model="ruleForm" :rules="rules" ref="formName" label-width="120px" class="demo-ruleForm"
        :class="{ 'form-rules-show': seeType }">

        <el-row>
          <el-col :span="12">
            <el-form-item label="公司名称：" prop="companyId">
              <el-cascader v-model="ruleForm.companyId" placeholder="请选择公司名称" :options="companyArray" :props="{
                checkStrictly: true,
                value: 'id',
                label: 'name',
                children: 'childList',
              }" @change="changeTreeItem" clearable :disabled="seeType"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="基地名称：" prop="baseId">
              <el-select v-model="ruleForm.baseId" placeholder="请选择基地名称" clearable @change="baseChange">
                <el-option v-for="item in baseArray" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="整理人员：" prop="baseUserId">
              <el-select v-model="ruleForm.baseUserId" placeholder="请选择整理人员" clearable @change="baseChange">
                <el-option v-for="item in userList" :key="item.id" :label="item.realName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发送内容：" prop="content">
              <el-input v-model="ruleForm.content" placeholder="请输入发送内容" clearable show-word-limit></el-input>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="整治时间：" prop="time">
              <el-date-picker @blur="timeFind" v-model="ruleForm.time" format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" range-separator="至" start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>


        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="发送图片：" prop="images">
              <MultipleImgUpload sirProps="image" :sirUrl="ruleForm.imagesArr" :limit="6" @upSuccess="upSuccess"
                :disabled="seeType"></MultipleImgUpload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('formName')">取 消</el-button>
        <el-button class="btn-light-blue" @click="submitForm('formName')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script type="text/ecmascript-6">
import MultipleImgUpload from "@/components/MultipleImgUpload.vue";
import { getDataTaskInspect, saveDataTaskInspect, getBoxFishponds } from "@/api/inspect";
import { getCompanyInfoTree } from "@/api/company";
import { getSysCompanyBases, getDataTaskRenovate, saveDataTaskRenovate, getSysUsers } from "@/api/system";

export default {
  components: {
    MultipleImgUpload
  },
  props: {
    addEditId: {
      type: String,
      default: "",
    },
    addEditStatus: {
      type: String,
      default: "add",
    },
    addEditIsDialog: {
      type: Boolean,
      default: false,
    },

  },
  data() {
    return {
      // 时间的快捷
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      fishpondArray: [],
      imagesArr: [],
      userList: [],
      ruleForm: {
        // 表单字段
        companyId: "",
        dealUserId: '1',
        time: ''

      },
      rules: {
        // 表单规则
        companyId: [
          { required: true, message: "请选择公司名称", trigger: "change" },
        ],
        baseId: [
          { required: true, message: "请选择基地名称", trigger: "change" },
        ],
        baseUserId: [
          { required: true, message: "请选择整理人员", trigger: "change" },
        ],
        imagesArr: [
          { required: true, message: "请上传发送图片", trigger: "change" },
        ],
        content: [
          { required: true, message: "请输入发送内容", trigger: "change" },
        ],
        fishpondId: [
          { required: true, message: "请选择鱼池", trigger: "change" },
        ],
        time: [
          { required: true, message: "请选择时间", trigger: "change" },
        ],

      },
      addEditIsDialog_c: false, // 弹窗是否显示
      seeType: false, // 是否禁用
      baseArray: [], // 基地集合
      companyArray: [], // 公司集合
      fishTypeArray: [], // 鱼类集合
      userType: "", // 用户类型（0超级管理员，1公司管理员）
      fishSex: [
        {
          value: 0,
          label: '未鉴定'
        },
        {
          value: 1,
          label: '雄'
        },
        {
          value: 2,
          label: '雌'
        }
      ]
    };
  },
  watch: {
    addEditIsDialog(val) {
      this.addEditIsDialog_c = val;
      if (this.addEditIsDialog_c) {
        // 添加
        if (this.addEditStatus == "add") {
          this.ruleForm.id = this.addEditId;
          // console.log(this.ruleForm);

          this.seeType = false;

        }

        // 编辑
        if (this.addEditStatus == "edit") {
          this.ruleForm.id = this.addEditId;
          this.seeType = false;
          this.getDetail();
        }

        // 查看
        if (this.addEditStatus == "see") {
          this.ruleForm.id = this.addEditId;
          this.seeType = true;
          this.getDetail();
        }

        this.userType = Number(window.localStorage.getItem("userType"));

        // 获取公司列表
        this.getCompanyInfoTree();

        this.getSysCompanyBases();
        // this.getSysUsers()
      }
    },
  },
  methods: {
    timeFind() {
      this.$forceUpdate();
      console.log(this.ruleForm.time);
      this.ruleForm.time = this.ruleForm.time
    },
    // 上传图片
    upSuccess(data) {
      this.ruleForm.imagesArr = data;
    },

    // 详情
    getDetail() {
      getDataTaskRenovate({ id: this.addEditId }).then((res) => {
        if (res.code == 200) {
          res.data.imagesArr =
            res.data.images != undefined ? res.data.images.split(",") : [];

          // this.$set(this.ruleForm, 'time', [res.data.startDateTime, res.data.endDateTime])
          // console.log(this.ruleForm.time);
          this.ruleForm = res.data;
          this.ruleForm.time = [res.data.startDateTime, res.data.endDateTime]
          // 获取公司列表
          this.getCompanyInfoTree();
          this.getSysCompanyBases();
          this.getBoxFishponds();
          this.getSysUsers()
          // this.getObjFishTypes();
        }
      });
    },

    // 提交
    submitForm(formName) {

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.ruleForm.images = this.ruleForm.imagesArr.toString();
          // console.log(this.ruleForm);
          this.ruleForm.startDateTime = this.ruleForm.time[0]
          this.ruleForm.endDateTime = this.ruleForm.time[1]
          // const params = new URLSearchParams();
          // params.append('baseId', this.ruleForm.baseId)
          // params.append('companyId', this.ruleForm.companyId)
          // params.append('content', this.ruleForm.content)
          // params.append('dealUserId', this.ruleForm.dealUserId)
          // params.append('fishpondId', this.ruleForm.fishpondId)
          // params.append('images', this.ruleForm.images)
          saveDataTaskRenovate(this.ruleForm).then((res) => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: res.msg,
              });

              // 关闭弹窗
              this.$parent.closeAddEdit();
              // 刷新列表
              this.$parent.onSubmit();
            }
          });
        }
      });
    },
    // 基地下拉切换
    baseChange() {
      // 获取鱼池列表
      this.getBoxFishponds();
    },
    // 获取鱼池列表
    getBoxFishponds() {
      // if (
      //   this.searchForm.boxId === "" ||
      //   this.searchForm.boxId == null
      // ) {
      //   return;
      // }
      // console.log(this.ruleForm);
      let a = {
        baseId: this.ruleForm.baseId,
        companyId: this.ruleForm.companyId,
      }
      getBoxFishponds(a).then((res) => {
        if (res.code == 200) {
          this.fishpondArray = res.data;
        }
      });
    },
    // 取消
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.$parent.closeAddEdit();
      this.ruleForm.imagesArr = []
    },
    // 获取公司列表
    getCompanyInfoTree() {
      if (this.ruleForm.userType === "") {
        return;
      }

      if (this.ruleForm.userType == 0) {
        // 超级管理员，公司只有一个总公司
        this.companyArray = [
          {
            id: 0,
            name: "总公司",
            parentId: 0,
          },
        ];
      } else {
        getCompanyInfoTree({}).then((res) => {
          if (res.code == 200) {
            this.companyArray = res.data;
          }
        });
      }
    },
    // 公司下拉切换
    changeTreeItem(val) {
      if (val) {
        this.ruleForm.companyId = val[val.length - 1];
      } else {
        this.ruleForm.companyId = "";
      }

      // this.ruleForm.baseId = "";
      // this.baseArray = [];
      // console.log(val);
      // this.getObjFishTypes(val)
      // 获取基地列表
      this.getSysCompanyBases();
      this.getSysUsers()
    },
    getSysUsers() {
      getSysUsers({ id: this.ruleForm.companyId }).then((res) => {
        if (res.code == 200) {
          this.userList = res.data;
          // console.log(this.userList);
        }
      });
    },
    // 获取基地列表
    getSysCompanyBases() {
      if (this.ruleForm.companyId === "" || this.ruleForm.companyId == null) {
        return;
      }

      getSysCompanyBases({ id: this.ruleForm.companyId }).then((res) => {
        if (res.code == 200) {
          this.baseArray = res.data;
        }
      });
    },
    // getObjFishTypes() {

    //   getObjFishTypes({ id: this.ruleForm.companyId }).then((res) => {
    //     if (res.code == 200) {
    //       this.fishTypeArray = res.data;

    //     }
    //   });
    // },
  },
};
</script>

<style lang="less" scoped>
.demo-ruleForm {
  width: 95%;
  margin: 0 auto;
  padding-top: 10px;
}

.el-cascader {
  width: 100%;
}

.el-select {
  width: 100%;
}
</style>
